#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
清除测试数据脚本
该脚本用于在部署前清除所有测试数据，但保留必要的结构和管理员用户。
"""

import os
import sys
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import app, db
from models import Issue, Comment, Tag, Milestone, User, IssueHistory, File
from werkzeug.security import generate_password_hash

# 确保在应用上下文内运行
with app.app_context():
    # 清除问题相关数据
    print("开始清除问题数据...")
    comment_count = Comment.query.delete()
    print(f"已删除 {comment_count} 条评论")
    
    issue_history_count = IssueHistory.query.delete()
    print(f"已删除 {issue_history_count} 条问题历史记录")
    
    file_count = File.query.delete()
    print(f"已删除 {file_count} 个文件记录")
    
    # 只删除非管理员创建的问题
    issue_count = Issue.query.filter(Issue.created_by != 1).delete()
    print(f"已删除 {issue_count} 个问题")
    
    # 保留基本标签，仅删除额外添加的标签
    basic_tags = ['bug', 'feature', 'task', 'question', 'documentation']
    tags_to_keep = Tag.query.filter(Tag.name.in_(basic_tags)).all()
    tag_ids_to_keep = [tag.id for tag in tags_to_keep]
    
    extra_tag_count = Tag.query.filter(Tag.id.notin_(tag_ids_to_keep)).delete()
    print(f"已删除 {extra_tag_count} 个额外标签")
    
    # 保留基本里程碑，仅删除额外添加的里程碑
    milestones_to_keep = Milestone.query.filter(Milestone.name.in_(['v1.0', 'v1.1'])).all()
    milestone_ids_to_keep = [ms.id for ms in milestones_to_keep]
    
    extra_milestone_count = Milestone.query.filter(Milestone.id.notin_(milestone_ids_to_keep)).delete()
    print(f"已删除 {extra_milestone_count} 个额外里程碑")
    
    # 除管理员外，删除其他用户
    user_count = User.query.filter(User.id != 1).delete()
    print(f"已删除 {user_count} 个非管理员用户")
    
    # 提交更改
    db.session.commit()
    print("测试数据清除完成！")
    
    # 检查管理员用户
    admin = User.query.get(1)
    if admin:
        print(f"管理员用户 '{admin.username}' 保留成功")
    else:
        print("警告：管理员用户不存在，将创建新的管理员用户")
        admin_password = generate_password_hash('admin123', method='sha256')
        admin = User(username='admin', email='admin@example.com', password=admin_password, is_admin=True)
        db.session.add(admin)
        db.session.commit()
        print('管理员用户创建成功：用户名=admin, 密码=admin123')

print("所有操作已完成！")